<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class TaskController extends AgoraPollsController {

    function _default() {
        $catnav_helper = & $this->helper('catnav');
        $catnav_helper->fromForum($this->id);

		$access_helper = & $this->helper('access');
		$access = $access_helper->getForumAccess($this->id);
		$this->view->assign('access',$access);
		
        $this->view->template = 'poll/multi';
    }

    function _continue_edit() {
    }

    function create() {
	
		if (!$this->agora_user['is_superadmin'] && $this->access_model->authenticate($this->agora_user['id'],$this->id,'use_captcha')) {
			$captcha = Agora::getPostVar('captcha');
			$c_key = Agora::getSessionVar('captcha');

			if (trim($captcha) !== trim($c_key) || !$captcha) {
				Agora::showMessage(Agora::lang('Bad captcha'));
				Agora::redirect(Agora::getRefferer());
			}
		}

        $poll_options = Agora::getPostVar('poll_option',array());
        $opt = array();
        foreach ($poll_options as $option) {
            $option = trim($option);
            if (!empty($option)) {
                $opt[] = $option;
            }
        }

        if (count($opt) < 2) {
            Agora::showMessage(Agora::lang('You need to set at least 2 options'));
            Agora::redirect(Agora::getRefferer());
        }

        if (trim(Agora::getPostVar('subject',''))=='') {
            Agora::showMessage(Agora::lang('You need to set subject'));
            Agora::redirect(Agora::getRefferer());
        }

		$parser = & $this->helper('parser');
        $topic_model = & Model::getInstance('TopicModel');
		$forum_model = & Model::getInstance('ForumModel');
		$forum = $forum_model->load($this->id);
		$approved = ($this->agora_user['is_superadmin'] || $this->agora_user['is_admin'] || $this->agora_user['is_moderator']) ? 1 : !(int)$forum['use_moderation'];

		$subscribe = Agora::getPostVar('subscribe',0);
		$subject = Agora::getPostVar('subject','No subject');
		$message = Agora::getPostVar('req_message','');
		$message = $parser->fix_broken_bbcode($message);
		$desc = Agora::getPostVar('desc','');
		$question = Agora::getPostVar('req_question','no question');
		$topic_icon = intval(Agora::getPostVar('topic_icon',0));
		$hide_smilies = Agora::getPostVar('hide_smilies',0);

		if ($approved) {
			// Trigger onBeforeCreatePoll Agora plugin event
			JPluginHelper::importPlugin('agora');
			$dispatcher =& JDispatcher::getInstance();
			$options= new JObject;
			$options->forum_id = $this->id;
			$options->topic_id = null;
			$options->subject = $subject;
			$options->message = $message;
			$options->desc = $desc;
			$options->user_name = $this->agora_user['username'];
			$options->user_id = $this->agora_user['id'];
			$options->question = $question;
			$options->poll_yes = '';
			$options->poll_no = '';
			$plg_result = $dispatcher->trigger('onBeforeCreatePoll', array(&$options)) ;
		}
		
		// Add poll, topic and post
        $topic_id = $topic_model->addPoll($this->id, $subject, $desc, $topic_icon, $this->agora_user['username'], $question, $approved);
        $post_id = $topic_model->addPost($topic_id, $this->id, $message, $this->agora_user['id'], $this->agora_user['username'], $hide_smilies, $approved);
        $this->model->add($topic_id, $opt, 2);
		
		// ugly, will fix it some day...
		$db = & AgoraDatabase::getInstance('agora_');
		$db->setQuery('UPDATE #__agora_topics SET last_post = ' . $db->Quote(AGORA_TIME) . ', last_post_id = ' . $db->Quote($post_id) . ', last_poster = ' . $db->Quote($this->agora_user['username']) . ', num_replies = num_replies+1 WHERE id = ' . $db->Quote($topic_id));
		$db->query();
		
		$topic = $topic_model->load($topic_id);
		
		if ($approved) {
			// Trigger onAfterCreatePoll Agora plugin event
			$options->topic_id 	= $topic_id;
			$plg_result =  $dispatcher->trigger('onAfterCreatePoll', array(&$options));

			// If AUP plugin exists - add user points
			$api_AUP = JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php';
			if (file_exists($api_AUP))	{
				require_once ($api_AUP);
				AlphaUserPointsHelper::newpoints( 'plgaup_newtopic_agora', '', '', Agora::lang('AUP_TOPIC'));
			}
			
			// Send notification to subscribed users
			$subscription_helper = & $this->helper('subscription');
			$subscription_helper->newPost($topic['last_post_id'], $this->id);

		} else {
			Agora::showMessage(Agora::lang('POST_MODERATION_MESSAGE'));
		}
		
		if ( $subscribe ) {
			$subscription_model = & Model::getInstance('SubscriptionModel');
			$subscription_model->add(array('user_id' => $this->agora_user['id'], 'topic_id' => $topic_id));
			Agora::showMessage(Agora::lang('You are now subscribed on topic ') . ' '  . AString::escape($subject)); 
		}
		
		// Send notification to mods and admins if the post is moderated
		if (!$approved) {
			$subscription_helper = &$this->helper('subscription');
			$subscription_helper->newPost($topic['last_post_id'], $topic['forum_id'], true);
		}
		
		if ($approved) {
			Agora::redirect(Agora::makeUrl(array('task'=>'topic','id'=>$topic_id)));
		} else {
			Agora::redirect(Agora::makeURL(array('task' => 'forum', 'id' => $topic['forum_id'])));
		}
    }

    function vote() {
        $poll = $this->model->load($this->id,'pollid');

        if (!$poll) {
            Agora::showError(Agora::lang('Invalid request (bad poll id)'));
            $this->redirect();
        }
        if ($poll['ptype'] != '2') {
            Agora::showError(Agora::lang('Invalid request (bad poll type)'));
            $this->redirect();
        }

        $voters = $poll['voters'];
        $votes = $poll['votes'];
        $voter = intval($this->agora_user['id']);

        if (!is_array($votes)) $votes = array();
        if (!is_array($voters)) $voters = array();

        if (in_array($voter,$voters)) {
            Agora::showError(Agora::lang('You already voted'));
            $this->redirect();
        }

        if (Agora::getPostVar('submit',null) !== null) {
            $options = Agora::getPostVar('options',array());

            foreach ($options as $key=>$value) {

                if (!empty($value) && array_key_exists($key, $options)) {
                    if (isset($votes[$key])) {
                        $votes[$key]++;
                    } else {
                        $votes[$key] = 1;
                    }
                }
            }

        }

        $voters[] = $voter;

        $this->model->setVotes($this->id, $votes,$voters);

        Agora::showMessage(Agora::lang('You vote accepted'));
        $this->redirect();
    }
}

?>
